package com.boruan.shengtangfeng.core.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.List;
import org.apache.oro.text.regex.*;
import org.apache.commons.lang3.StringUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class VideoUtil {

    public static void main(String[] args) throws ParseException {
        Integer l = getDuration("http://file.stftt.cn/upload/img/content/0/1_20190102172005_1065831876513750.mp4");
        System.out.println(l);
    }

    /**
     * 通过ppmpeg计算视频长度，返回秒数
     */
    public static Integer getDuration(String videoUrl) {
        //videoUrl=StringUtils.replace(videoUrl, "public.stftt.com","shengtangfeng-public.oss-cn-huhehaote.aliyuncs.com");
        videoUrl=StringUtils.replace(videoUrl, "public.stftt.com","shengtangfeng-public.oss-cn-huhehaote-internal.aliyuncs.com");
        videoUrl=StringUtils.replace(videoUrl, "shengtangfeng-public.oss-cn-huhehaote.aliyuncs.com","shengtangfeng-public.oss-cn-huhehaote-internal.aliyuncs.com");
        String str = processVideo(videoUrl);
        if (StringUtils.isNotBlank(str)) {
            String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
            PatternCompiler compiler = new Perl5Compiler();
            try {
                Pattern patternDuration = compiler.compile(regexDuration, Perl5Compiler.CASE_INSENSITIVE_MASK);
                PatternMatcher matcherDuration = new Perl5Matcher();
                if (matcherDuration.contains(str, patternDuration)) {
                    MatchResult re = matcherDuration.getMatch();
                    String result=re.group(1);
                    System.out.println("提取出播放时间 ===" + result);
                    String[] strs=StringUtils.split(result,":");
                    Integer i=0;
                    i+=Integer.parseInt(strs[0])*3600;
                    i+=Integer.parseInt(strs[1])*60;
                    i+=Integer.parseInt(StringUtils.split(strs[2],".")[0]);
                    return i;
                }
            } catch (MalformedPatternException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    // ffmpeg能解析的格式：（asx，asf，mpg，wmv，3gp，mp4，mov，avi，flv等）
    private static String processVideo(String inputPath) {
        List commend = new java.util.ArrayList();

        commend.add("/usr/bin/ffmpeg");// 可以设置环境变量从而省去这行
        commend.add("ffmpeg");
        commend.add("-i");
        commend.add(inputPath);

        try {

            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commend);
            builder.redirectErrorStream(true);
            Process p = builder.start();

            // 1. start
            BufferedReader buf = null; // 保存ffmpeg的输出结果流
            String line = null;
            // read the standard output

            buf = new BufferedReader(new InputStreamReader(p.getInputStream()));

            StringBuffer sb = new StringBuffer();
            while ((line = buf.readLine()) != null) {
                sb.append(line);
                continue;
            }
            int ret = p.waitFor();// 这里线程阻塞，将等待外部转换进程运行成功运行结束后，才往下执行
            // 1. end
            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }
}
